# -*- coding: utf-8 -*-
# @Time      : 2025-08-01
# @Author    : 2023090007@ahdy.edu.cn
# @File      : system
# @Desc  
import socket
import redis
from common.mysql_client import MySQLClient
from common.redis_distributed_lock import RedisDistributedLock

class System(object):

    options = None

    @classmethod
    def InitOptions(cls, options):
        cls.options = options


    @classmethod
    def DbClient(cls):
        config = cls.options.get('db_config', {})
        db_config = {
            "host": config.get('host', "localhost"),
            "user": config.get('user', "root"),
            "password": config.get('password', "root@20250801"),
            "database": config.get("db_name", "dispatch"),
            "port": config.get('port', 3306),
        }

        # 创建客户端实例
        db = MySQLClient(**db_config)
        return db

    @classmethod
    def RedisLock(cls):
        config = cls.options.get('redis_config', {})
        redis_client = redis.Redis(
            host=config.get('host', 'localhost'),
            port=config.get('port', 6379),
            db=0,
            decode_responses=True
        )
        
        # 创建分布式锁实例
        lock = RedisDistributedLock(
            redis_client=redis_client,
            lock_key="distributed_lock:example",
            expire_seconds=10,
            retry_times=5,
            retry_delay=0.2
        )
        return lock


    @classmethod
    def GetHostIp(cls):
        try:
            # 连接到外部服务器，不发送任何数据
            with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
                s.connect(("8.8.8.8", 80))
                public_ip = s.getsockname()[0]
            return public_ip
        except Exception:
            return "unknown public ip"


